package designpatterns.obsever.code;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 调用
 */
public class Client {
    public static void main(String[] args) throws InterruptedException {
        // 气象站
        WeatherServer weatherServer = new WeatherServer();
        // 气象站异步更新天气
        Thread thread = new Thread(() -> {
            long start = System.currentTimeMillis();
            while (true) {
                // 天气变化,使用随机数代替变化消息
                WeatherChangeEvent event = new WeatherChangeEvent(getRandomNum(), getRandomNum());
                weatherServer.notifyAllObservers(event);
                // 2分钟关闭
                if (System.currentTimeMillis() - start > 2 * 60 * 1000) {
                    break;
                }
                // 10s更新一次天气
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        // 百度天气
        BaiduWeather baiduWeather = new BaiduWeather();
        weatherServer.register(baiduWeather);

        // 2s后腾讯天气上线
        TimeUnit.SECONDS.sleep(2);
        TenantsWeather tenantsWeather = new TenantsWeather();
        weatherServer.register(tenantsWeather);

        // 30s后百度下线
        TimeUnit.SECONDS.sleep(30);
        weatherServer.remove(baiduWeather);

        thread.join();
    }

    /**
     * 获取一个随机数
     * @return
     */
    public static float getRandomNum() {
        Random random = new Random();
        return (random.nextFloat() * 10) + 1;
    }

}
